//
//  Date+Extension.swift
//  Slaughter
//
//  Created by Zwb on 2018/1/24.
//  Copyright © 2018年 zwb. All rights reserved.
//

import UIKit

extension Date {
 
        
    // MARK: 当月结束日期    传入字符串 2020-10-10   返回  2020-10-31
    static func endOfSomeMonth(_ someday:String) -> String {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
        let nowDayDate = dateFormatter.date(from: someday)
            
            let calendar = Calendar.current
            var components = DateComponents()
            components.month = 1
//            if returnEndTime {
//                components.second = -1
//            } else {
                components.day = -1
//            }
            //startOfCurrentMonth
            let currentMonth = calendar.dateComponents([.year, .month], from: nowDayDate!)
            let startOfMonth = calendar.date(from: currentMonth)
            let endOfMonth = calendar.date(byAdding: components, to: startOfMonth!)
            
            let day = dateFormatter.string(from: endOfMonth!)
            return day
        }
    
    
    // MARK: 获取某一天所在的周一和周日
    //  返回第一天日期  2023-03-27  最后一天日期 2023-04-02  和全日期简写数组  27 28 29 30 31  1  2
    static func getWeekTime(_ dateStr: String) -> (String,String,[String]) {
          let dateFormatter = DateFormatter()
          dateFormatter.dateFormat = "yyyy-MM-dd"
          let nowDate = dateFormatter.date(from: dateStr)
          let calendar = Calendar.current
          let comp = calendar.dateComponents([.year, .month, .day, .weekday], from: nowDate!)
            
          // 获取今天是周几
          let weekDay = comp.weekday
          // 获取今天是几号
          let day = comp.day
            
          // 计算当前日期和本周的星期一和星期天相差天数
          var firstDiff: Int
          var lastDiff: Int
          // weekDay = 1;
          if (weekDay == 1) {
              firstDiff = -6;
              lastDiff = 0;
          } else {
              firstDiff = calendar.firstWeekday - weekDay! + 1
              lastDiff = 8 - weekDay!
          }
       
        
      
           
          // 在当前日期(去掉时分秒)基础上加上差的天数
          var firstDayComp = calendar.dateComponents([.year, .month, .day], from: nowDate!)
          firstDayComp.day = day! + firstDiff
           let firstDayOfWeek = calendar.date(from: firstDayComp)
        
          var lastDayComp = calendar.dateComponents([.year, .month, .day], from: nowDate!)
          lastDayComp.day = day! + lastDiff
          let lastDayOfWeek = calendar.date(from: lastDayComp)
    
          let firstDay = dateFormatter.string(from: firstDayOfWeek!)
          let lastDay = dateFormatter.string(from: lastDayOfWeek!)
       
        var dayArr = [String]()
        for i in 0..<7 {
            let d = somedayAfter(i, date: firstDay)
            let s = String(d.suffix(2))
            dayArr.append(s)
        }
   
          return (firstDay,lastDay,dayArr)
      }
    // 获取某一天是星期几 (0: 异常, 1~7: 周日->周一 -> ...周六)
        static func getWeekDay(date: Date) -> Int {
            let calendar = Calendar(identifier: .chinese)
            let dateCmps = calendar.dateComponents([.weekday], from: date)
            return dateCmps.weekday ?? 0
        }
        
    static func formatWeek(week: Int) -> String {
            switch week {
            case 1:
                return " 周日"
            case 2:
                return " 周一"
            case 3:
                return " 周二"
            case 4:
                return " 周三"
            case 5:
                return " 周四"
            case 6:
                return " 周五"
            case 7:
                return " 周六"
            default:
                return ""
            }
        }
    // 提前几个月1号-01
    static func preMonths_1(_ preMonths: Int) -> String {
        
        let month = Date().dateBySubtractingMonths(preMonths)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        return formatter.string(from: month) + "-01"
    }
    // 延后几个月1号-01
    static func sufMonths_1(_ preMonths: Int) -> String {
         let month = Date().dateByAfterMonths(preMonths)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        return formatter.string(from: month) + "-01"
    }
    
    /// 提前天数的日期 字符串
    static func todayPres(_ predays: Int) -> String {
    
        let interval = TimeInterval(24 * 60 * 60 * predays)
        let data = Date(timeIntervalSinceNow: -interval)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let curDate = formatter.string(from: data)
        return curDate
    }
    /// 提前天数的日期 字符串
    static func somedayPres(_ predays: Int,date:String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let interval = TimeInterval(24 * 60 * 60 * predays)
        let data = Date(timeInterval: -interval, since: formatter.date(from: date)!)
         let curDate = formatter.string(from: data)
        return curDate
    }
    
    
    /// 提前天数的日期  日期型
      static func todayPresDate(_ predays: Int) -> Date {
      
          let interval = TimeInterval(24 * 60 * 60 * predays)
          let data = Date(timeIntervalSinceNow: -interval)
          return data
      }
   
    /// 提前天数的日期    的    1号
     static func firstDayOfPresMonth(_ predays: Int) -> String {
         let interval = TimeInterval(24 * 60 * 60 * predays)
         let data = Date(timeIntervalSinceNow: -interval)
         let formatter = DateFormatter()
         formatter.dateFormat = "yyyy-MM"
         let curDate = formatter.string(from: data)
        
         return curDate + "-01"
     }

    // 往后的天数的日期
       static func todayAfter(_ afterdays: Int) -> String {
       
           let interval = TimeInterval(24 * 60 * 60 * afterdays)
           let data = Date(timeIntervalSinceNow: interval)
           let formatter = DateFormatter()
           formatter.dateFormat = "yyyy-MM-dd"
           let curDate = formatter.string(from: data)
           return curDate
       }
    
    /// 往后的天数的日期
    static func somedayAfter(_ predays: Int,date:String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let interval = TimeInterval(24 * 60 * 60 * predays)
        let data = Date(timeInterval: interval, since: formatter.date(from: date)!)
         let curDate = formatter.string(from: data)
        return curDate
    }
    
 
    
    // 提前几个月的今天
      static func preMonthsWithNowday(_ preMonths: Int) -> String {
          
          let month = Date().dateBySubtractingMonths(preMonths)
          let formatter = DateFormatter()
          formatter.dateFormat = "yyyy-MM"
        
          let form = DateFormatter()
           form.dateFormat = "dd"
          return formatter.string(from: month) + "-" + form.string(from: Date())
       
      }
 
   
       static func preMonths(_ preMonth: Int) -> String {
           
           let month = Date().dateBySubtractingMonths(preMonth)
           let formatter = DateFormatter()
           formatter.dateFormat = "yyyy-MM"
           return formatter.string(from: month)
        
       }
 
    
    ///现在时间 yyyy-MM-dd HH:mm
    static var nowTimeToMinute:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        return formatter.string(from: Date())
    }
    ///现在时间 yyyy-MM-dd HH
    static var nowTimeToHour:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH"
        return formatter.string(from: Date())
    }
    
    //
    // 某天 字符串
     static func date2String(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: date)
    }
    
    ///现在时间 yyyy-MM-dd-HH-mm-ss
       static var yyyyMMddHHmmss:String {
           let formatter = DateFormatter()
           formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
           return formatter.string(from: Date())
       }
    
    ///现在时间 yyyy-MM-dd HH:mm:ss
    static var nowTimeToSecond:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return formatter.string(from: Date())
    }
    ///现在时间 yyyyMMddHHmmss
       static var nowTimeToString:String {
           let formatter = DateFormatter()
           formatter.dateFormat = "yyyyMMddHHmmss"
           return formatter.string(from: Date())
       }
    ///现在时间 yyyy-MM-dd HH:mm:ss
    static var mmddhhmmss:String {
           let formatter = DateFormatter()
           formatter.dateFormat = "MMddHHmmss"
           return formatter.string(from: Date())
       }
    ///现在时间 HH:mm
    static var nowTime:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter.string(from: Date())
    }
    ///现在时间
    static var nowTimeSecond:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss"
        return formatter.string(from: Date())
    }
    ///现在时间 HH:mm
       static var dd:String {
           let formatter = DateFormatter()
           formatter.dateFormat = "dd"
           return formatter.string(from: Date())
       }
    
    ///现在时间 HH
       static var HH:String {
           let formatter = DateFormatter()
           formatter.dateFormat = "HH"
           return formatter.string(from: Date())
       }
    
    //每调用一次月份向下跳一月，跨年则为下一年1月   都是 1号
    static func getNextYearAndMonth(dateStr:String = Date.today) -> String {
        let formatter1 = DateFormatter(withFormat: "yyyy-MM-dd", locale: "")
        let dateee = formatter1.date(from: dateStr)
        let formatter2 = DateFormatter(withFormat: "yyyy", locale: "")
        let year = formatter2.string(from: dateee!)
        let formatter3 = DateFormatter(withFormat: "MM", locale: "")
        let month = formatter3.string(from: dateee!)
        
           var nextYear = Int(year)!
           var nextMonth = Int(month)! + 1
           if nextMonth > 12 {
               nextMonth = 1
               nextYear += 1
           }
          
        let nextMStr = nextMonth > 9 ? "\(nextMonth)" : "0\(nextMonth)" // 一位数前面补0
        
           //Swift可以同时返回多个值，返回值类型为元组
           return String(nextYear) + "-" + nextMStr + "-01"
       }
    

    //每调用一次月份向下跳一月，跨年则为下一年1月
    static func getNextYearAndMonth(year:String = Date.currentYear,month:String = Date.currentMonth) -> String {
        var nextYear = Int(year)!
        var nextMonth = Int(month)! + 1
        if nextMonth > 12 {
            nextMonth = 1
            nextYear += 1
        }
        //Swift可以同时返回多个值，返回值类型为元组
        return String(nextYear) + "-" + String(nextMonth)
    }
    
    /// 本月的第一天  yyyy-MM-dd
    static var firstDateOfMonth:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        return formatter.string(from: Date()) + "-01"
    }
   //本月开始日期
    static var startOfCurrentMonth:Date {
        let date = Date()
        let calendar = NSCalendar.current
        let components = calendar.dateComponents(
            Set<Calendar.Component>([.year, .month]), from: date)
        let startOfMonth = calendar.date(from: components)!
        return startOfMonth
    }
     
    //本月结束日期   returnEndTime 到秒
    static func endOfCurrentMonth(returnEndTime:Bool = false) -> Date {
        let calendar = NSCalendar.current
        var components = DateComponents()
        components.month = 1
        if returnEndTime {
            components.second = -1
        } else {
            components.day = -1
        }
         
        let endOfMonth =  calendar.date(byAdding: components, to: Date.startOfCurrentMonth)!
        return endOfMonth
    }
    static func endDateCurrentMonth() -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: endOfCurrentMonth())
    }
    
   /// 今年第一个月  yyyy-MM
    static var firstMonthOfYear:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy"
        return formatter.string(from: Date()) + "-01"
    }
   
    /// 今年第一天  yyyy-MM-dd
    static var firstDateOfYear:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy"
        return formatter.string(from: Date()) + "-01-01"
    }
    
    
    /// 今天  yyyy-MM-dd
    static var today:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: Date())
    }
    
    /// 本月  yyyy-MM
    static var currentMonth:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        return formatter.string(from: Date())
    }
    /// 本月  MM
    static var thisMonth:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM"
        return formatter.string(from: Date())
    }
    
    
    /// 今年  yyyy
    static var currentYear:String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy"
        return formatter.string(from: Date())
    }
    
    func today(_ dateFormat: String = "yyyy-MM-dd HH:mm") -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = dateFormat
        return formatter.string(from: self)
    }
    
    
    // 把秒 转为  --:--:--
   static func getHHMMSSFormSS(seconds:Int) -> String {
        let str_hour = NSString(format: "%02ld", seconds/3600)
        let str_minute = NSString(format: "%02ld", (seconds%3600)/60)
        let str_second = NSString(format: "%02ld", seconds%60)
        let format_time = NSString(format: "%@:%@:%@",str_hour,str_minute,str_second)
        return format_time as String
    }

    // 提前天数的月份
   static func todayPresMonth(_ predays: Int) -> String {
        
        let interval =  TimeInterval(24 * 60 * 60 * predays)
        let data = Date(timeIntervalSinceNow: -interval)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        let curDate = formatter.string(from: data)
        return curDate
    }
    
    
     
    static func preMonth(yyyymm: String) -> String {
 
        let current = yyyymm
        let month = String(current.suffix(2))
        let year = String(current.prefix(4))

         var intMonth = Int(month)! - 1
        var intYear =  Int(year)!
        if intMonth == 0 {
            intMonth = 12
            intYear -= 1
        }
        var tempMonth = ""
         if intMonth < 10 {
            tempMonth = "0\(intMonth)"
         } else {
            tempMonth = "\(intMonth)"
          }
         return String(intYear) + "-" + tempMonth
    }
    static func nextMonth(yyyymm: String) -> String {
        let current = yyyymm
        let month = String(current.suffix(2))
        let year = String(current.prefix(4))

         var intMonth = Int(month)! + 1
        var intYear =  Int(year)!
        if intMonth == 13 {
            intMonth = 1
            intYear += 1
        }
        var tempMonth = ""
         if intMonth < 10 {
            tempMonth = "0\(intMonth)"
         } else {
            tempMonth = "\(intMonth)"
          }
         return String(intYear) + "-" + tempMonth
    }
    
    //每调用一次月份向上跳一月，跨年则为上一年12月
    static func moveUp(month months: Int) -> String {
        
        assert(months < 12, "超出12月")
        let current = Date.currentMonth
        let month = String(current[current.index(current.endIndex, offsetBy: -2)...])
        var prevYear = Int(Date.currentYear)!
        var prevMonth = Int(month)! - months
        if prevMonth == 0 {
            prevMonth = 12
            prevYear -= 1
        } else if prevMonth < 0 {
            prevMonth += 12
            prevYear -= 1
        }
        
        var tempMonth = String(prevMonth)
        if prevMonth < 10 {
            tempMonth = "0\(prevMonth)"
        }
        
        return String(prevYear) + "-" + tempMonth
    }
    
    
    /// 时间比较 和当前时间比    返回相差的秒数
    ///  killNow   --》   true   （传入时间 - 当前时间） false  （当前时间  -  传入时间  ）
    static func timeComparison(inDateStr:String?,killNow:Bool = true) -> Int? {
        if let notice_start_dt = inDateStr {
            
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            
            let dateFormatter2 = DateFormatter()
            dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm"
            let dateFormatter3 = DateFormatter()
            dateFormatter3.dateFormat = "yyyy-MM-dd"
            
            var endDDD = Date()
            if let endD = dateFormatter.date(from: notice_start_dt) {
                endDDD = endD
            }
            
            if let endD2 = dateFormatter2.date(from: notice_start_dt) {
                endDDD = endD2
            }
            
            if let endD3 = dateFormatter3.date(from: notice_start_dt) {
                endDDD = endD3
            }
            var timeNumber:Int?
            if killNow {
                 timeNumber = Int(endDDD.timeIntervalSince1970-dateFormatter.date(from: Date.nowTimeToSecond)!.timeIntervalSince1970)
            } else {
                timeNumber = Int(dateFormatter.date(from: Date.nowTimeToSecond)!.timeIntervalSince1970-endDDD.timeIntervalSince1970)
            }
 
            return timeNumber
            
        } else {
            return nil
        }
    }
    
    static func change2Date(str:String) -> Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateFormatter2 = DateFormatter()
        dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm"
        let dateFormatter3 = DateFormatter()
        dateFormatter3.dateFormat = "yyyy-MM-dd"
        
        if let endD = dateFormatter.date(from: str) {
            return endD
        }
        else if let endD2 = dateFormatter2.date(from: str) {
            return endD2
        }
         else if let endD3 = dateFormatter3.date(from: str) {
             return endD3
         } else {
             return nil
         }
    }
    
    
    // 时间比较 格式要求 yyyy-MM-dd HH:mm:ss
    static func timeComparison(aStr:String?,bStr:String?) -> Int? {
        
        if let aDx = Date.change2Date(str: aStr.unwrap), let bDx = Date.change2Date(str: bStr.unwrap) {
            var timeNumber:Int?
          
                timeNumber = Int(aDx.timeIntervalSince1970 - bDx.timeIntervalSince1970)
               return timeNumber
         } else {
            return nil
        }
    }
    
    // 提前天数的月-01
    func earlyMonthfor(_ month: Int) -> String {
        let interval = TimeInterval(24 * 60 * 60 * month)
        let data = Date(timeIntervalSinceNow: -interval)
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        return formatter.string(from: data) + "-01"
    }
 
    
    // 提前天数的月份
    func earlyMonth(_ month: Int) -> String {
        let interval =  TimeInterval(24 * 60 * 60 * month)
        let data = Date(timeIntervalSinceNow: -interval)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        return formatter.string(from: data)
    }
    
    func timeIntervalToTime(timeInterval: TimeInterval) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter.string(from: Date(timeIntervalSince1970: timeInterval))
    }
 
}

//当前日期 后9位
func dateOfTimeSub9() -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "MddHHmmss"
    return formatter.string(from: Date())
}
/// 计算时间差   lastDateStr - preDateStr
func daysDifference(lastDateStr: String, preDateStr: String) -> Int? {

    guard  !lastDateStr.isEmpty ,  !preDateStr.isEmpty  else {
        return 0
    }
    guard  lastDateStr.count == 10 ,  preDateStr.count == 10  else {
        return 0
    }
    let dm: DateFormatter = DateFormatter()
    dm.dateFormat = "yyyy-MM-dd"
    let D_DAY = 86400

    let firstDate: Date = dm.date(from: lastDateStr)!
    let secondDate: Date = dm.date(from: preDateStr)!

    let interval: TimeInterval = firstDate.timeIntervalSince(secondDate)
    let days = (Int(interval)) / D_DAY
    return days
}

// 指定年月的第一天
func firstDayFromYearMonth(_ year:String,_ month:String) -> String {
    return "\(year)-\(month)-01"
}
// 指定年月的最后一天
func lastDayFromYearMonth(_ year:String,_ month:String) -> String {
    return "\(year)-\(month)-" + getDaysInMonth(year: Int(year)!, month: Int(month)!)
}

//计算指定月天数
func getDaysInMonth( year: Int, month: Int) -> String
{
    let calendar = NSCalendar.current
    
    let startComps = NSDateComponents()
    startComps.day = 1
    startComps.month = month
    startComps.year = year
    
    let endComps = NSDateComponents()
    endComps.day = 1
    endComps.month = month == 12 ? 1 : month + 1
    endComps.year = month == 12 ? year + 1 : year
    let startDate = calendar.date(from: startComps as DateComponents)
    let endDate = calendar.date(from: endComps as DateComponents)
    
    //比较两个日期的天数
    let diff = calendar.dateComponents([.day], from: startDate!, to: endDate!)
    return "\(diff.day!)"
}


//
// 某天 返回改成 未解包，如报错需调整
func dateFromString(_ date: String) -> Date? {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    return formatter.date(from:date)
}

func dateTimeFromString(_ date: String) -> Date? {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    return formatter.date(from:date)
}
 

// 提前时长的日期
func getPrevDay(_ n: Double) -> String {
    let date = Date().addingTimeInterval(n * 60 * 60 * 24)
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    return formatter.string(from: date)
}
// 提前时长的日期 a_date 某天 day  往前减的天数
func getPrevDayFrom(a_date:String, day: Double) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    let date = formatter.date(from: a_date)!.addingTimeInterval(-day * 60 * 60 * 24)
     return formatter.string(from: date)
}

//每调用一次月份向上跳一月，跨年则为上一年12月
func getPrevYearAndMonth(_ n: Int) -> String {
    
    assert(n < 12, "超出12月")
    
    let month = String(Date.currentMonth[Date.currentMonth.index(Date.currentMonth.endIndex, offsetBy: -2)...])
    var prevYear = Int(Date.currentYear)!
    var prevMonth = Int(month)! - n
    if prevMonth == 0 {
        prevMonth = 12
        prevYear -= 1
    } else if prevMonth < 0 {
        prevMonth += 12
        prevYear -= 1
    }
    
    var tempMonth = String(prevMonth)
    if prevMonth < 10 {
        tempMonth = "0\(prevMonth)"
    }
    
    return String(prevYear) + "-" + tempMonth
}

// MARK: - ---------提前天数------

// 提前天数的月-01
func todayPres_1(_ predays: Int) -> String {
    
    let interval = TimeInterval(24 * 60 * 60 * predays)
    
    let data = Date(timeIntervalSinceNow: -interval)
    
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM"
    let curDate = formatter.string(from: data) + "-01"
    return curDate
}
 


// MARK: - ---------提前月数------

func todayPreMonths_new(_ preMonths: Int, dType: Date.DateType, isBefore: Bool) -> String {
    
    var num = preMonths
    
    let date1 = Date()
    
    let date = date1.datePreMonths(&num, dType: dType, isBefore: isBefore)
    
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd hh-MM-ss"
    let curDate = formatter.string(from: date)
    return curDate
}





// 提前月数的年份-01
func todayPreMonthsYear_1(_ preMonths: Int) -> String {
    if preMonths <= 0 {
        return Date.firstDateOfMonth
    }
    var year = Int(Date.currentYear)!
    var month = Int(Date.currentMonth)!
    
    let y = preMonths / 12
    let  n = preMonths % 12
    
    if month - n > 0 {
        year -= y
        month -= n
    } else if month - n == 0 {
        year -= y - 1
        month = 12
        
    } else if month - n < 0 {
        year -= y - 1
        month += 12 - n
    }
    
    return "\(year)-01"
}

// MARK: - -------- 提前年数 -----------
// 提前年数的月份-01
func todayPreYear_1(_ preYears: Int) -> String {
    if preYears <= 0 {
        return Date.firstMonthOfYear
    }
    let year = Int(Date.currentYear)!
    let num = year - preYears
    if num <= 0 {
        return Date.firstMonthOfYear
    } else {
        return "\(num)-01"
    }
}
// 提前年数的日期-01-01
func todayPreYear_1_1(_ preYears: Int) -> String {
    if preYears <= 0 {
        return Date.firstMonthOfYear
    }
    let year = Int(Date.currentYear)!
    let num = year - preYears
    if num <= 0 {
        return Date.firstDateOfYear
    } else {
        return "\(num)-01-01"
    }
}
// 提前年数的年份
func todayPreYear(_ preYears: Int) -> String {
    if preYears <= 0 {
        return Date.currentYear
    }
    let year = Int(Date.currentYear)!
    let num = year - preYears
    if num <= 0 {
        return Date.currentYear
    } else {
        return "\(num)"
    }
}


extension Date {
    
    enum DateType: Int {
        case era = 0,  // 当前日期（不变）
        year,          // 年（可变）
        month,         // 月（可变）
        day,           // 日（可变）
        hour,          //
        minute,
        second,
        nanosecond,     // 十亿分之一秒
        weekday,        // 天数
        weekdayOrdinal, // 周序数
        quarter,        // 四分之一 刻
        weekOfMonth,    // 月周数
        weekOfYear,     // 年周数
        yearForWeekOfYear
    }
    
    func datePreMonths(_ num:inout Int, dType: DateType, isBefore: Bool) -> Date {
        
        if isBefore == true {
            num *= -1
        }
        
        var components = DateComponents()
        
        switch dType {
        case DateType.era:
            components.era = num
        case DateType.year:
            components.year = num
        case DateType.month:
            components.month = num
        case DateType.day:
            components.day = num
        case DateType.hour:
            components.hour = num
        case DateType.minute:
            components.minute = num
        case DateType.second:
            components.second = num
        case DateType.nanosecond:
            components.nanosecond = num
        case DateType.weekday:
            components.weekday = num
        case DateType.weekdayOrdinal:
            components.weekdayOrdinal = num
        case DateType.quarter:
            components.quarter = num
        case DateType.weekOfMonth:
            components.weekOfMonth = num
        case DateType.weekOfYear:
            components.weekOfYear = num
        case DateType.yearForWeekOfYear:
            components.yearForWeekOfYear = num
            
        }
        
        let calenar = Calendar(identifier: Calendar.Identifier.gregorian)
        let date = (calenar as NSCalendar?)?.date(byAdding: components, to: self, options: [])
        
        return date!
    }
    
    func dateBySubtractingMonths(_ months: Int) -> Date {
        var dateComp = DateComponents()
         dateComp.month = (months * -1)
        return (Calendar.current as NSCalendar).date(byAdding: dateComp, to: self, options: NSCalendar.Options.matchFirst)!
    }
    func dateByAfterMonths(_ months: Int) -> Date {
        var dateComp = DateComponents()
         dateComp.month = (months * +1)
        return (Calendar.current as NSCalendar).date(byAdding: dateComp, to: self, options: NSCalendar.Options.matchFirst)!
    }
    func dateBySubtractingDays(_ days: Int) -> String {
        var dateComp = DateComponents()
        
        dateComp.day = (days * -1)
        let date = (Calendar.current as NSCalendar).date(byAdding: dateComp, to: self, options: NSCalendar.Options.matchFirst)!
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        return formatter.string(from: date)
    }
    
}

extension String {
    
    func stringDatePreDay(_ days: Int) -> String {
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        guard let dateCurr = formatter.date(from: self) else {
            return ""
        }
        
        var dateComp = DateComponents()
        dateComp.day = days
        let date = (Calendar.current as NSCalendar).date(byAdding: dateComp, to: dateCurr, options: NSCalendar.Options.matchFirst)!
        
        return formatter.string(from: date)
    }
}

func transforMonth(_ date: String) -> (String, String) {
    if date == "" {
        return ("", "")
    } else {
        let year = String(date[..<date.index(date.firstIndex(of: "-")!, offsetBy: -1)])
        let month = String(date[date.index(date.firstIndex(of: "-")!, offsetBy: 1)...])
        
        switch month {
        case "01", "03", "05", "07", "08", "10", "11":
            return (date + "-" + "01", date + "-" + "31")
        case "04", "06", "09", "10", "12":
            return (date + "-" + "01", date + "-" + "30")
        case "02":
            
            if let tyear = Int(year) {
                if tyear % 4 == 0 {
                    return (date + "-" + "01", date + "-" + "29")
                } else {
                    return (date + "-" + "01", date + "-" + "28")
                }
            }
            return ("", "")
        default:
            return ("", "")
        }
    }
}

 
